<template>
  <div>
    <div class="app-container">
      <h-table-list
        border
        type="local"
        :page-sizes="[10,20]"
        :data="device_repair_days.records"
        @size-change="handleSizeChange"
        :columns="columns"
        :paginationInfo="paginationInfo"
        :form-options="formOptions"
      >
      
        <ListOpearteButton />
        <template slot="operate-column" slot-scope="scope">
          <tableButton :row="scope.row" />
        </template>
      </h-table-list>
    </div>
    <DownloadIdentify   
      @cancel="cancel"
      @update="dialogSubmit"
      :visible.sync="dialogFormVisible"
     
      :title="ruleForm.id?'编辑维修排班':'新建维修排班'">
   <el-form    :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm" :label-position="'top'" size="small">
  <el-form-item  label="排班名称" prop="scheduleName">
    <el-input   v-model="ruleForm.scheduleName"></el-input>
  </el-form-item>
      <el-form-item  label="人员" prop="userIds" >
     <el-select multiple v-model="ruleForm.userIds" >
                <el-option
                  v-for="e in app.allUser"
                  :key="e.value||e"
                  :label="e.label||e"
                  :value="e.value||e"
                />
              </el-select>
  </el-form-item>
 <el-form-item  label="排班时间" prop="time">
    <h-table-list
        border
        type="local"
        :showPagination="false"
        :data="dateData"
        @size-change="handleSizeChange"
        :columns="columns1"
      >
      <template slot="chooseDate" slot-scope="scope">
        <!-- <el-time-picker  is-range
        v-model="time[scope.$index]"
    range-separator="至"></el-time-picker> -->
     <el-time-picker
        is-range
        v-model="time[scope.$index]"
       

    >
  </el-time-picker>
      </template>
      </h-table-list>
 </el-form-item>
   
 
   </el-form>
  </DownloadIdentify>
  </div>
</template>

<script>
import { mapState, mapMutations } from "vuex";
import waves from "@/directive/waves"; // waves directive
import DownloadIdentify from "@/components/FormDialog";
import Pagination from "@/components/Pagination"; // secondary package based on el-pagination
import ListOpearteButton from "@/components/AllButton/button2";
import tableButton from "@/components/AllButton/button3";
import data from "./const";
import { parseTime,listTotree } from "@/utils";
const weekObj={1:'星期日',2:'星期一',3:'星期二',4:'星期三',5:'星期四',6:'星期五',7:'星期六'}
export default {
  name: "device_repair_days",
  components: {
    DownloadIdentify,
    Pagination,
    tableButton,
    ListOpearteButton,
  },
  directives: { waves },
  filters: {
    typeFilter(type) {
      return calendarTypeKeyValue[type];
    },
  },
  data() {
    return {
      time:[
         [new Date(2016, 9, 10, 8, 40), new Date(2016, 9, 10, 9, 40)]
      ],
    //  timeString: [new Date(2016, 9, 10, 8, 40), new Date(2016, 9, 10, 9, 40)],
      dialogFormVisible:false,
      loadList: false,
      showPwd:false,
       ruleForm: {
          userIds: [],
          scheduleName: '',
        },
         rules: {
          userName: [
            { required: true, message: '请输入userName', trigger: 'blur' },
            { min: 6, max: 20, message: '长度在 1 到 5 个字符', trigger: 'blur' }
          ],
          realName: [
            { required: true, message: '请输入姓名', trigger: 'blur' }
          ],
          password:[
            { required: true, message: '密码6-20位，包含字母、数字、符号中至少两种，字母区分大小写', trigger: 'blur' }
          ],
           organId: [
            { required: true, message: '请选择', trigger: 'blur' }
          ],
          positionsId: [
            { required: true, message: '请选择', trigger: 'blur' }
          ],
          phone:[
            { required: true, message: '请输入正确手机号', trigger: 'blur' }
          ],
          userType:[
            { required: true, message: '请选择账号类别', trigger: 'blur' }
          ],
          },
          
      paginationInfo: {
        sizeChange: (e) => {
          console.log(e);
        },
        currentChange: (e) => {
        
          this.$store.dispatch("device_repair_days/setListSearchParams", {
            current: e,
          });
          this.getList(
            Object.assign({}, this.$store.state.device_repair_days.listSearchParams)
          );
        },
        current: 1,
        total: 10 ,
      },
      formOptions: {
        inline: true,
        submitBtnText: "搜索",
        showResetBtn:false,
        showSearchBtn:false,
        searchParamsHandler: () => {
          console.log("搜索"); 
          this.getList(this.$store.state.device_repair_days.listSearchParams);
        },
        changevalue: (params) => {
          //   const forms=this.formOptions.forms.map(e=>{
          //      const key=e.prop
          //      e.defaultValue=params[key]
          //     return e
          //    })
          //  console.log(forms)
          console.log(params);
          this.$store.dispatch("device_repair_days/setListSearchParams", params);
        },
        resetBtnCallback: () => {
          this.$store.dispatch("device_repair_days/setListSearchParams", {});
          this.getList(this.$store.state.device_repair_days.listSearchParams);
        },
       forms: [
        ],
      },
       columns: [
         { type:"index",prop: "repNumber", label: "序号"},
        { prop: "scheduleName", label: "排班名称" },

        {
          prop: "time",
          label: "排班时间",
          width: 800,
          render: (row) => {
            let dataStr=""
            if(row.time){
              const data= row.time.map(e=>{
              const { weekType,startTime,endTime } =e
             dataStr=dataStr +weekObj[weekType] +startTime+"-"+endTime+"  "
            })
            }
            
            return dataStr
          },
        },
        {
          prop: "userIds",
          label: "排班人员",
          width: 300,
          render: (row) =>{
            let dataStr=""
            if(row.userIds){
              const data= this.$store.state.app.allUser.map(e=>{
                if(row.userIds.includes(e.value)){
                    dataStr=dataStr+e.label+","
                }
              
            })
            }
            
            return dataStr
          }
        },
        {
          prop: "operate",
          label: "操作",
          minWidth: 180,
          slotName: "operate-column",
          fixed: "right",
        },
      ],
      columns1: [
         { prop:"weekType", label: ""},
        { prop: "scheduleName", label: "起止时间",slotName:"chooseDate",minWidth:"200" }],
      dateData:[{weekType:weekObj[1]},{weekType:weekObj[2]},{weekType:weekObj[3]},{weekType:weekObj[4]},{weekType:weekObj[5]},{weekType:weekObj[6]},{weekType:weekObj[7]}],  
      tableData: [],
    };
  },

  watch: {
    formChange: () => {},
  },
  computed: {
    ...mapState(["device_repair_days","app"]),
  },
  created() {
    //初始获取几个基本数据,分别为操作状态,按钮权限等
    // (this.formOptions.forms = this.formOptions.forms.map((e) => {
    //   const key = e.prop;
    //   const data = this.$store.state.device_repair_days.listSearchParams;
    //   e.defaultValue = data[key] || "";
    //   return e;
    // })),
      //this.submitHandler=this.searchWithParams
      this.$store
        .dispatch(this.$store_url_button, {
          add: this.add,
         // export: this.export,
          delete: this.delete,
          edit: this.edit,
          detail: this.detail,
         // using: this.using,
          //useless: this.useless,
          //downloadTemplete: this.downloadTemplete,
          //downloadIdentify: this.downloadIdentify, 
          //resetPwd:this.resetPwd
        })
        .then(async () => {
        
           //const department=listTotree(this.$store.state.app.allCode.department)
           //const allDuty=this.$store.state.app.allDuty
           //this.$set(this.formOptions.forms[3],"options",department)
           //this.$set(this.formOptions.forms[4],"options",allDuty)
          this.getList(); // 表格数据
        });

    // this.listQuery=this.$store.state.basicEquipment.listSearchParams||{}  //操作状态
  },
  methods: {
      formatDateToTime(date){
        const time=new Date(date)
       
        return time.getHours()+":"+time.getMinutes()
      },
      cancel(){
      this.dialogFormVisible=false
    },
      dialogSubmit(){ 
       
        //const time=this.formatDateToTime(this.time[0][0])
 
        const time=this.time.map((e,i)=>{
          const data={}
          data.weekType=i+1
          data.startTime=e?this.formatDateToTime(e[0]):""
          data.endTime=e?this.formatDateToTime(e[1]):""
          return data
        })
        console.log(time)
       
      this.$refs["ruleForm"].validate((valid) => {
          if (valid) {
           const data=this.ruleForm
           data.time=time
          //  data.users=this.ruleForm.users.map(e=>{
          //    return {repUserId:e}
          //  })
           this.$store.dispatch("device_repair_days/saveInfo",this.ruleForm).then(res=>{
            this.getList()
            this.dialogFormVisible=false
           }).catch(err=>{
 
           })
          
          } else {
            console.log('error submit!!');
            return false;
          }
        });
       
    },
    //自定义该业务模块下的按钮方法
     //自定义该业务模块下的按钮方法
    using(row) {
       this.$store.dispatch("device_repair_days/useUserInfo",row.id).then(res=>{
            this.getList()
            //this.dialogFormVisible=false
           }).catch(err=>{
 
           })
    },
    useless(row) {
        this.$store.dispatch("device_repair_days/uselessUserInfo",row.id).then(res=>{
            this.getList()
            //this.dialogFormVisible=false
           }).catch(err=>{
 
           })
    },
    add(row) {
      this.ruleForm.id=""
       this.ruleForm={}
       this.tableData=[{weekType:weekObj[1]},{weekType:weekObj[2]},{weekType:weekObj[3]},{weekType:weekObj[4]},{weekType:weekObj[5]},{weekType:weekObj[6]},{weekType:weekObj[7]}]
       this.time=[]
       this.showPwd=true
      this.dialogFormVisible=true
    },
    edit(row) {
        this.ruleForm = JSON.parse(JSON.stringify(row));
        this.showPwd=false
      this.tableData=[{weekType:weekObj[1]},{weekType:weekObj[2]},{weekType:weekObj[3]},{weekType:weekObj[4]},{weekType:weekObj[5]},{weekType:weekObj[6]},{weekType:weekObj[7]}]
      this.time=[
      row.time[0]?[new Date(2016, 9, 10, row.time[0].startTime.split(":")[0], row.time[0].startTime.split(":")[1]),new Date(2016, 9, 10, row.time[0].endTime.split(":")[0], row.time[0].endTime.split(":")[1])]:"",
     row.time[1]?[new Date(2016, 9, 10, row.time[1].startTime.split(":")[0], row.time[1].startTime.split(":")[1]),new Date(2016, 9, 10, row.time[1].endTime.split(":")[0], row.time[1].endTime.split(":")[1])]:"",
        row.time[2]?[new Date(2016, 9, 10, row.time[2].startTime.split(":")[0], row.time[2].startTime.split(":")[1]),new Date(2016, 9, 10, row.time[2].endTime.split(":")[0], row.time[2].endTime.split(":")[1])]:"",
            row.time[3]?[new Date(2016, 9, 10, row.time[3].startTime.split(":")[0], row.time[3].startTime.split(":")[1]),new Date(2016, 9, 10, row.time[3].endTime.split(":")[0], row.time[3].endTime.split(":")[1])]:"",
             row.time[4]?[new Date(2016, 9, 10, row.time[4].startTime.split(":")[0], row.time[4].startTime.split(":")[1]),new Date(2016, 9, 10, row.time[4].endTime.split(":")[0], row.time[4].endTime.split(":")[1])]:"",
           row.time[5]?[new Date(2016, 9, 10, row.time[5].startTime.split(":")[0], row.time[5].startTime.split(":")[1]),new Date(2016, 9, 10, row.time[5].endTime.split(":")[0], row.time[5].endTime.split(":")[1])]:"",
           row.time[6]?[new Date(2016, 9, 10, row.time[6].startTime.split(":")[0], row.time[6].startTime.split(":")[1]),new Date(2016, 9, 10, row.time[6].endTime.split(":")[0], row.time[6].endTime.split(":")[1])]:""
      ]
      this.dialogFormVisible=true
    },
    downloadIdentify(row) {
      console.log("下载设备标识卡");
      this.dialogFormVisible = true;
    },
    async downloadTemplete(ids) {
      console.log("下载导出模板");
      const download=await this.$store.dispatch("device_repair_days/downloadTemplete");
      //window.open(download.)
      console.log(download)
    },
    delete(row) {
      console.log(row);
      this.$confirm(
        `该账号删除后不可恢复，确认删除？请先确保：

1.该账号无审批任务

2.该账号不在任一审批配置中`,
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          this.$store.dispatch("device_repair_days/deleteDeviceInfo",row.id).then(response=>{
           this.$message({
            type: "success",
            message: "删除成功!",
          });
          this.getList();
          }).catch(()=>{ 
            this.$message({
            type: "info",
            message: "删除失败",
          })})
         
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    update() {},
    detail(row) {
      console.log(row);

      localStorage.setItem("/device-basic/component/detail/index", row.id);
      this.$router.push("/device-basic/component/detail/index");
    },
    import() {},
    export() {
      console.log("导出");
      this.$store.dispatch("device_repair_days/exportFile");
    },
    //弹窗的关闭
    cancel() {
      console.log("关闭弹窗");
      this.dialogFormVisible = false;
    },
    //更新弹窗数据
    updateDialog() {
      console.log("更新并关闭弹窗");
      this.dialogFormVisible = false;
    },
    //搜索按钮
    searchWithParams() {
      console.log("搜索");
    },
    async getList(args) {
      // this.listLoading = true
      console.log(args);
      await this.$store.dispatch("device_repair_days/requestDeviceList", args);
      this.paginationInfo.total=this.$store.state.device_repair_days.total
    },
    handleFilter(args) {
      this.listQuery.page = 1;
      this.getList(args);
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: "操作成功",
        type: "success",
      });
      row.status = status;
    },
    sortChange(data) {
      const { prop, order } = data;
      if (prop === "id") {
        this.sortByID(order);
      }
    },
    sortByID(order) {
      if (order === "ascending") {
        this.listQuery.sort = "+id";
      } else {
        this.listQuery.sort = "-id";
      }
      this.handleFilter();
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        importance: 1,
        remark: "",
        timestamp: new Date(),
        title: "",
        status: "published",
        type: "",
      };
    },
    handleCreate() {
      // this.resetTemp();
      // this.dialogStatus = "create";
      // this.dialogFormVisible = true;
      // this.$nextTick(() => {
      //   this.$refs["dataForm"].clearValidate();
      // });
      this.dialogFormVisible = true;
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row); // copy obj
      this.temp.timestamp = new Date(this.temp.timestamp);
      this.dialogStatus = "update";
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate();
      });
    },
    handleDelete(row) {
      this.$notify({
        title: "成功",
        message: "删除成功",
        type: "success",
        duration: 2000,
      });
      const index = this.list.indexOf(row);
      this.list.splice(index, 1);
    },
  },
};
</script>
